package star.cloud.asme.flowable.form.leave;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import star.cloud.asme.base.dto.Result;
import star.cloud.asme.base.mybatis.IBaseServiceImpl;
import star.cloud.asme.flowable.processInstance.HqProcessInstanceService;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class LeaveServiceImpl extends IBaseServiceImpl<LeaveMapper, Leave> implements LeaveService {

    private final LeaveMapper leaveMapper;

    private final HqProcessInstanceService hqProcessInstanceService;

    private final RuntimeService runtimeService;


    @Override
    public Result<Leave> getOneByCondition(String columnName, Object columnValue) {
        LambdaQueryWrapper<Leave> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Leave::getProcessInstanceId, columnValue);
        Leave leave = leaveMapper.selectOne(queryWrapper);
        setCreatorAndUpdater(leave);
        return Result.ok(leave);
    }

    @Override
    public Result<Leave> insertOne(Leave entity) {
        leaveMapper.insert(entity);
        setCreatorAndUpdater(entity);
        Map<String, Object> variables = new HashMap<>();
        variables.put("days", entity.getDays());
        entity.setVariables(variables);
        Result<ProcessInstance> processInstanceResult = hqProcessInstanceService.startProcessInstanceById(generateStartProcessInstanceParams(entity));
        setProcessInstanceInfo(entity, processInstanceResult.getBody());
        updateById(entity);
        return Result.ok(entity);
    }

    @Override
    public Result<Leave> updateOne(Leave entity) {
        updateById(entity);
        runtimeService.setProcessInstanceName(entity.getProcessInstanceId(), entity.getProcessInstanceName());
        Leave leave = leaveMapper.selectById(entity.getId());
        setCreatorAndUpdater(leave);
        return Result.ok(leave);
    }

    void setVariables(String executionId, LeaveVariables leaveVariables) {
        Map<String, Object> variables = new HashMap<>();
        runtimeService.setVariables(executionId, variables);
    }


}